require.config({
    baseUrl: "./",
    paths: {
        // vue: location.search == '?debug' ? "js/lib/vue.2.6.12" : 'js/lib/vue.2.6.12.min',
        Vuex: 'js/lib/vuex.3.5.1.min',
        HeyUI: 'js/lib/heyui',
        vueRouter: 'js/lib/vue-router.3.5.1.min',
        heyGlobal: 'js/lib/hey-global',
        axios: 'js/lib/axios',
        sortablejs: 'js/lib/sortable.min',//CDN 'http://www.itxst.com/package/sortable/Sortable.min',
        vuedraggable: 'js/lib/vuedraggable.umd.min',//CDN 'http://www.itxst.com/package/vuedraggable/vuedraggable.umd.min',
        plupload: 'js/lib/plupload.min',
        moxie: 'js/lib/moxie.min',
        vs: 'js/vs',
        echarts: 'js/lib/echarts.min',//'https://cdn.bootcdn.net/ajax/libs/echarts/5.1.2/echarts.min',
        lodash_debounce: 'https://cdn.jsdelivr.net/npm/lodash.debounce@4.0.8/index.min',
        XLSX: 'js/lib/xlsx.full.min'
    },
    // shim: {
    //     HeyUI: {
    //         deps: ['css!../../css/heyui-blue.css', 'css!../../css/icons.css']
    //     }
    // }
})
window.load = function (path, callback) {
    require([path], function (md) {
        if (path.endsWith(".vue")) {
            require.undef("vue-loader!" + path)
        } else {
            require.undef(path)
        }

        callback && callback(md)
    })
}
// framework.init("#app", {
//                 template: '<div id="app"><router-view/></div>', router: router,
//             })
define('framework', ['vue', 'axios', 'HeyUI'], function (Vue, axios, HeyUI) {
    let ajax = {
        get: function (uri, params) {
            params = params || {};
            return axios.get(uri, {params: params});
        },
        delete: function (uri, params) {
            params = params || {};
            return axios.delete(uri, {params: params});
        },
        put: function (uri, params) {
            params = params || {};
            return axios.put(uri, params);
        },
        post: function (uri, params) {
            params = params || {};
            return axios.post(uri, params);
        },
        formPost: function (uri, params) {
            params = params || {};
            let data = new FormData();
            Object.keys(params).forEach(function (key) {
                let v = params[key];
                if (v == null) {
                    return
                }
                if (v.constructor == Array) {
                    for (let i = 0; i < v.length; i++) {
                        data.append(key, v[i]);
                    }
                } else {
                    data.append(key, v);
                }
            });
            return axios.post(uri, data);
        },
        upload: function (uri, params) {
            params = params || {};
            let data = new FormData();
            Object.keys(params).forEach(function (key) {
                let v = params[key];
                if (v == null) {
                    return
                }
                if (v.constructor == Array) {
                    for (let i = 0; i < v.length; i++) {
                        data.append(key, v[i]);
                    }
                } else {
                    data.append(key, v);
                }
            });
            return axios({
                url: uri,
                method: 'POST',
                data: data,
                onUploadProgress: function (progressEvent) {
                    if (progressEvent.loaded == progressEvent.total) {
                        HeyUI.$Loading.close();
                    } else {
                        let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
                        //console.log('上传 ' + complete)
                        HeyUI.$Loading('文件上传中 ' + complete);
                    }
                }
            })//axios.post(uri, data);
        },
        download(path) {
            if (axios.defaults.baseURL) {
                path = axios.defaults.baseURL + path
            }
            let elemIF = document.createElement('iframe')
            elemIF.src = path;
            elemIF.style.display = 'none';
            elemIF.onload = function () {
                document.body.removeChild(elemIF);
            }
            document.body.appendChild(elemIF)
        }
    }

    function dateFormat(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
            "H+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        var week = {
            "0": "/u65e5",
            "1": "/u4e00",
            "2": "/u4e8c",
            "3": "/u4e09",
            "4": "/u56db",
            "5": "/u4e94",
            "6": "/u516d"
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        if (/(E+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]);
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;

    }

    function formatNumber(num, pattern) {
        var strarr = num ? num.toString().split('.') : ['0'];
        var fmtarr = pattern ? pattern.split('.') : [''];
        var retstr = '';
        // 整数部分
        var str = strarr[0];
        var fmt = fmtarr[0];
        var i = str.length - 1;
        var comma = false;
        for (var f = fmt.length - 1; f >= 0; f--) {
            switch (fmt.substr(f, 1)) {
                case '#':
                    if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                    break;
                case '0':
                    if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                    else retstr = '0' + retstr;
                    break;
                case ',':
                    comma = true;
                    retstr = ',' + retstr;
                    break;
            }
        }
        if (i >= 0) {
            if (comma) {
                var l = str.length;
                for (; i >= 0; i--) {
                    retstr = str.substr(i, 1) + retstr;
                    if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
                }
            } else retstr = str.substr(0, i + 1) + retstr;
        }
        retstr = retstr + '.';
        // 处理小数部分
        str = strarr.length > 1 ? strarr[1] : '';
        fmt = fmtarr.length > 1 ? fmtarr[1] : '';
        i = 0;
        for (var f = 0; f < fmt.length; f++) {
            switch (fmt.substr(f, 1)) {
                case '#':
                    if (i < str.length) retstr += str.substr(i++, 1);
                    break;
                case '0':
                    if (i < str.length) retstr += str.substr(i++, 1);
                    else retstr += '0';
                    break;
            }
        }
        return retstr.replace(/^,+/, '').replace(/\.$/, '');
    }

    let format = function (value, format) {
        if (arguments.length == 2) {
            if (format.startsWith("#") || format.startsWith("0")) {
                return formatNumber(value, format);
            } else {
                if (value == null) {
                    return "";
                }
                if (value instanceof Date) {

                } else {
                    value = new Date(value);
                }
                return dateFormat(format, value);
            }
        }
        format = value;
        if (format.startsWith("#") || format.startsWith("0")) {
            return function (val) {
                return formatNumber(val, format);
            }
        } else {
            return function (val) {
                if (val == null) {
                    return "";
                }
                if (val instanceof Date) {

                } else {
                    val = new Date(val);
                }
                return dateFormat(format, val);
            }
        }

    }
    let DataSource = function (uri, pageable) {
        this.data = [];
        this.params = {};
        this.loading = false;
        this.uri = uri;
        let self = this;
        if (pageable) {
            this.pagination = {
                page: 0,
                size: 10,
                total: 0
            }
        }
        this.param = function (params) {
            Object.assign(self.params, params)
            return this;
        }
        this.setParam = function (name, value) {
            this.params[name] = value;
            return this;
        }
        this.load = function (params, fn) {
            self.loading = true;
            if (params) {
                if (params instanceof Function) {
                    fn = params;
                    params = self.params;
                }
            } else {
                params = self.params;
            }
            if (self.pagination) {
                params.pageNo = self.pagination.page;
                params.pageSize = self.pagination.size;
            }
            ajax.get(self.uri, params).then(resp => {
                self.loading = false;
                if (resp.data) {
                    let data = resp.data;
                    if (fn) {
                        data = fn(data);
                    }
                    self.data.splice(0, self.data.length);
                    self.data.push(...data);
                }
                if (self.pagination && resp.total) {
                    self.pagination.total = resp.total;
                }
            }).catch(e => {

            })
            return this;
        }
    }

    Vue.use(HeyUI)
    Vue.prototype.$axios = axios
    Vue.prototype.$ajax = ajax
    Vue.prototype.$priv = function (code) {
        let user = this.$store.state.user
        if (user.username == 'admin') {
            return true
        }
        let permissions = user.permissions
        if (!permissions) {
            return false
        } else {
            return permissions.indexOf(code) > -1
        }
    }
    Vue.prototype.$role = function (code) {
        if (localStorage.username == 'admin') {
            return true
        }
        let privs = localStorage.roles
        if (!privs) {
            return false
        } else {
            return privs.split(",").indexOf(code) > -1
        }
    }

    //导入组件
    Vue.component('FileInput', function (resolve) {
        require(['coms/FileInput.vue'], resolve)
    })
    Vue.component('MonacoEditor', function (resolve) {
        require(['coms/MonacoEditor.vue'], resolve)
    })
    Vue.component('Chart', function (resolve) {
        require(['coms/Echarts.vue'], resolve)
    })
    Vue.prototype.$Prompt = function (title, defaultValue) {
        return new Promise(resolve => {
            this.$Modal({
                component: {
                    vue: {
                        data() {
                            return {
                                title: title,
                                value: defaultValue || ''
                            }
                        },
                        methods: {
                            cancel() {
                                this.$emit('close');
                            },
                            success() {
                                if (this.value) {
                                    resolve(this.value)
                                    this.$emit('close');
                                } else {
                                    this.$Message("没有内容")
                                }
                            }
                        },
                       render: function (_c) {
                            let self=this;
                            return _c('div', [_c('header', {staticClass: "h-modal-header"}, [title]), _c('div', {staticStyle: {"padding": "10px"}}, [_c('input', {
                                directives: [{
                                    name: "model",
                                    rawName: "v-model",
                                    value: (this.value),
                                    expression: "value"
                                }],
                                staticStyle: {"width": "100%"},
                                attrs: {"type": "text"},
                                domProps: {"value": (this.value)},
                                on: {
                                    input: function ($event) {
                                        if ($event.target.composing) return;
                                        self.value = $event.target.value
                                    }
                                }
                                })])
                                , _c('footer', {staticClass: "h-modal-footer"}, [_c('Button', {on: {"click": this.cancel}}, ["取消"]), _c('Button', {
                                    attrs: {"color": "primary"},
                                    on: {"click": this.success}
                                }, ["确认"])], 1)])
                        }
                    }
                }
            })
        })

    }
    Vue.filter('format', format)
    let routed = {}
    return {
        Vue,
        ajax,
        axios,
        util: {
            fields(obj, fields) {
                let ret = {}
                if (obj == null || fields == null) {
                    return ret;
                }
                for (let f of fields.split(',')) {
                    if (obj.hasOwnProperty(f)) {
                        ret[f] = obj[f]
                    }
                }
                return ret;
            },
            fold(obj, fields) {//将对应字段的数组用','拼接
                if (obj == null || fields == null) {
                    return obj;
                }
                if (!fields) {
                    return obj;
                }
                let result = {};
                Object.assign(result, obj)
                for (let f of fields.split(',')) {
                    if (obj[f]) {
                        result[f] = obj[f].join(',')
                    }
                }
                return result;
            },
            unfold(obj, fields) {//将对应字段的字符串用','拆封
                if (obj == null || fields == null) {
                    return obj;
                }
                if (!fields) {
                    return obj;
                }
                let result = {};
                Object.assign(result, obj)
                for (let f of fields.split(',')) {
                    if (obj[f]) {
                        result[f] = obj[f].split(',')
                    }
                }
                return result;
            },
            mapToKv(data) {
                if (!data) {
                    return []
                }
                let r = []
                let keys = Object.keys(data).sort((a, b) => a > b ? 1 : -1);
                for (let k of keys) {
                    r.push({key: k, title: data[k]})
                }
                return r;
            },
            clean(value) {//清空数据
                if (value == null) {
                    return;
                }
                if (value instanceof Array) {
                    value.splice(0, value.length)
                } else {
                    Object.keys(value).forEach(k => {
                        value[k] = null
                    })
                }
            }
        },
        // framework: framework,
        HeyUI: HeyUI,
        format: format,
        DataSource: DataSource,
        init: function (target, idx, options) {
            if (options && options.baseURL) {
                axios.defaults.baseURL = options.baseURL
            }
            let idxPage = {
                render: function (c) {
                    return c('div',
                        {
                            attrs: {
                                id: "app"
                            }
                        }, [c('router-view')], 1)
                }
            }
            Object.assign(idxPage, idx)
            new Vue(idxPage).$mount(target)
            let perLoader = document.getElementById("per-loader");
            if (perLoader) {
                perLoader.style.display = 'none'
            }

        }
    }
})
//组件定义
//define('')
